package kyssion.leetcode.num151_200;

public class code168_Excel表列名称 {
    public static void main(String[] args) {
        System.out.println(new code168_Excel表列名称().convertToTitle(
                27
        ));
    }

    StringBuilder item;

    public String convertToTitle(int n) {
        if (n <= 0) {
            return "";
        }
        if (n <= 26) {
            return String.valueOf((char) ('A' - 1 + n));
        }
        item = new StringBuilder();
        ans(1, n);
        return item.toString();
    }

    private long ans(long maxBefore, long n) {
        if (n < maxBefore) {
            return n;
        }
        long s = ans(maxBefore * 26, n - maxBefore);
        item.append((char) ('A' + s / maxBefore));
        return s % maxBefore;
    }

    /**
     * 通过公式进行计算 all = 26*(26*(26*a+b)+c)+d
     * 但是题目中有要求最小是1
     * 那么公式就变成了
     * all = 26*(26*(26*(a+1)+b+1)+c+1)+d+1
     *
     * @param n
     * @return
     */
    public String convertToTitle2(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            n--;
            int k = n % 26;
            sb.append((char) (k + 'A'));
            n /= 26;
        }
        return sb.reverse().toString();
    }
}
